/*
 * Loads CTParse and runs redirecting. This is the main component of CrunchTime, but it is probably the smallest and simplest.
 */
var prevURI = "code.google.com/p/crunchtime";
/*
 * The preferences interface. We have this so that we can get the preferences-defined redirect page.
 */
var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.crunchtime."); //the prefs service
/*
 * The CTParseService. Because it's a service, it only creates an instance if no other instance has been created. 
 */
var parse = Components.classes["@crunch.time/ctparseservice;1"].createInstance(Components.interfaces.CTParseServiceInt);
var crunchTimeLoader = {
    /*
     * The previous URI, saved so that we can have a referrer when redirecting. It is set to the last page that we went to, so if it's a redirect page, then we put the redirect.
     */
	
    //add the listener to the progress
init: function() {
	//add scheduled blocking event based on the current date compared to preferences prevDate
	var prevDateString = prefs.getCharPref("prevdate");
	var prevDate = new Date(prevDateString);
	var currentDate = new Date();
	if ((prevDate.getDate() != currentDate.getDate()) && (prevDate.getMonth() != currentDate.getMonth()) && (prevDate.getFullYear() != currentDate.getFullYear()))
	{
		parse.addScheduledToTasks("i","k");
	}
	
	var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	var hour = currentDate.getHours();
	if (hour <10)
		hour = "0"+currentDate.getHours();
	var minute = currentDate.getMinutes();
	if (minute <10)
		minute = "0"+currentDate.getMinutes();
	var day = currentDate.getDate();
	if (day <10)
		day = "0"+currentDate.getDate();
	var dateString = monthname[currentDate.getMonth()] +" "+ day+", " + currentDate.getFullYear() +" "+hour+":"+minute+":00";
	
	// Set char date to the current date so we will not add the scheduled task again
	prefs.setCharPref("prevdate", dateString);
	
	//alert("adding progress listener\n");
	gBrowser.addProgressListener(crunchTime_URLBarListener, Components.interfaces.nsIWebProgress.NOTIFY_LOCATION);
	
},
	
    //remove the listener to the progress bar
uninit: function() {
	//alert("removing progress listener\n");
	gBrowser.removeProgressListener(crunchTime_URLBarListener);
},
	
    //process a URL and if we should be blocking it, do so
processURL: function(URI) {
    var URLString = URI.asciiSpec;
    //dump(URLString + " : " + typeof(URLString) +  "\n");
    if(parse.shouldBlock(this.sanitize(URLString))){
		alert("You have been blocked by CrunchTime. Redirecting...");
		var redirect = prefs.getCharPref("redirectsite");
		//dump("REDIRECTING TO: " + redirect + "\n");
		//	gBrowser.loadURI(redirect,  "about:blank", 'UTF-8'); //load the new page with the previus page as the referrer
		gBrowser.loadURI(redirect);
		prevURI = redirect;//set the redirect to the previuous URI, so that we can refer with that if we so choose
		return true;//we did block
    }
    prevURI = this.sanitize(URLString); //save the new page so that we can
    return false;
    
},
    
sanitize: function(URI) {
	var sanitized;//The sanatized URI
	if(URI.substr(0,7) == "http://") { //If we have a http:// block, remove it
	    sanitized = URI.substring(7,URI.length);
	}
	else //otherwise, we need to use the entire URI
	    sanitized = URI;
	sanitized = sanitized.substring(0, sanitized.indexOf("/")); //We don't want anything after the root DNS. So, no slashes.
	return sanitized;
}
};

/*
 * A URLBarListener makes sure that we never change the location in the URL bar without checking to make sure that we're not slowing down.
 * This probably slows down browsing a little, but hopefully not too much.
 */

var crunchTime_URLBarListener = {
    /*
     * QueryInterface, used so that we can interact with XPCOM components. This makes crunchTime_URLBarListener an XPCOM component.
     */
QueryInterface: function(aIID) {
	if(aIID.equals(Components.interfaces.nsIWebProgressListener) ||
	   aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
	   aIID.equals(Components.interfaces.nsISupports))
	    return this;
	throw Components.results.NS_NOINTERFACE;
},
    /*
     * On location change is called when the location in the URL bar changes. When that happens, we want to check the URL.
     */
onLocationChange: function(aProgress, aRequest, aURI) {
	//alert("location change");
	crunchTimeLoader.processURL(aURI);
},
    /*
     * The rest of these functions are required for nsIWebProgressListener. Thus, we must have them, but we do not provide an implementation.
     */
onStateChange: function(a, b, c, d) {},
onProgressChange: function(a, b, c, d, e,f) {},
onStatusChange: function(a, b, c, d) {},
onSecurityChange: function(a, b, c) {}
};

window.addEventListener("load", function() {crunchTimeLoader.init();}, false);
window.addEventListener("unload", function() {crunchTimeLoader.uninit();}, false);
